﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.X509;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace XLB.ExtensionMethod.Files
{
    /// <summary>
    /// 文件操作相关
    /// </summary>
    public class FileHelper
    {
        /// <summary>
        /// base64转换为图片
        /// </summary>
        /// <param name="base64image"></param>
        /// <returns></returns>
        public static Image Base64ToImage(string base64image)
        {
            byte[] bytes = Convert.FromBase64String(base64image);

            MemoryStream memStream = new MemoryStream(bytes);

            BinaryFormatter binFormatter = new BinaryFormatter();

            Image img = (Image)binFormatter.Deserialize(memStream);

            return img;
        }

        /// <summary>
        /// 解析base64编码获取图片
        /// </summary>
        /// <param name="base64Code"></param>
        /// <returns></returns>
        private static Bitmap Base64ToImg(string base64Code)
        {
            MemoryStream stream = new MemoryStream(Convert.FromBase64String(base64Code));
            return new Bitmap(stream);
        }

        /// <summary>
        /// 接收Base64编码格式的图片并保存到指定位置
        /// </summary>
        /// <param name="file">base64文件</param>
        /// <param name="path">保存地址</param>
        /// <param name="title">图片名称</param>
        /// <returns>返回图片名称及后缀</returns>
        public static string UploadBase64Image(string file, string path, string title)
        {
            var suffixText = file.Split(',')[0];

            var baseText = file.Split(',')[1];

            //获取文件储存路径
            //string basePath = AppDomain.CurrentDomain.BaseDirectory; //获取当前项目所在目录
            string suffix = ""; //文件的后缀名根据实际情况
            if (suffixText.Contains("jpeg")) suffix = ".jpg";
            else if (suffixText.Contains("png")) suffix = ".png";
            else if (suffixText.Contains("gif")) suffix = ".gif";

            string strPath = path + title + suffix;  //basePath +

            //获取图片并保存
            Base64ToImg(baseText).Save(strPath);

            return path + title + suffix; // 返回图片名称及后缀
        }


        /// <summary>
        /// 读取指定路径的文件中的内容
        /// </summary>
        /// <param name="jsonFilePath"></param>
        /// <returns></returns>
        public static string ReadFileInfo(string jsonFilePath)
        {
            string message = string.Empty;
            using (System.IO.StreamReader file = System.IO.File.OpenText(jsonFilePath))
            {
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    JArray o = (JArray)JToken.ReadFrom(reader);
                    message = o.ToString();

                }
            }
            return message;
        }


        /// <summary>
        /// 下载网络文件到指定文件夹
        /// </summary>
        /// <param name="url">被下载文件网络地址</param>
        /// <param name="path">保存文件夹</param>
        /// <param name="fileName">文件名</param>
        public static void DownLoadFile(string url, string path, string fileName)
        {
            //调用示例：FileHelper.DownLoadFile(imageUrl, path, fileName);
            WebClient webClient = new WebClient();
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            WriteBytesToFile(path + "/" + fileName, GetBytesFromUrl(url));
        }

        private static byte[] GetBytesFromUrl(string url)
        {
            byte[] bytes;
            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
            WebResponse myResp = myReq.GetResponse();
            Stream stream = myResp.GetResponseStream();
            using (BinaryReader br = new BinaryReader(stream))
            {
                bytes = br.ReadBytes(500000);
                br.Close();
            }

            myResp.Close();
            return bytes;
        }

        private static void WriteBytesToFile(string fileName, byte[] content)
        {
            FileStream fs = new FileStream(fileName, FileMode.Create);
            BinaryWriter w = new BinaryWriter(fs);
            try
            {
                w.Write(content);
            }
            finally
            {
                fs.Close();
                w.Close();
            }
        }

        /// <summary>
        /// 爬取指定网站图片示例
        /// </summary>
        public async void CrawlingoutImage(string url)
        {
            if (string.IsNullOrEmpty(url))
            {
                url = "https://ourartnet.com/Siku_03/0782/0782_088_114/index.htm"; // 替换为你想爬取图片的网站  示例网站
            }


            string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Files/";
            using (HttpClient client = new HttpClient())
            {

                string content = await client.GetStringAsync(url);
                MatchCollection matches = Regex.Matches(content, @"<img[^<>]+");

                foreach (Match match in matches)
                {
                    string src = Regex.Match(match.Value, @"src=""([^""]+)""").Groups[1].Value;
                    if (!string.IsNullOrEmpty(src))
                    {
                        try
                        {
                            string imageUrl = new Uri(new Uri(url), src).AbsoluteUri;
                            //https://ourartnet.com/Siku_03/0782/0782_088_114/thumbnails/3055_jpg.jpg
                            //https://ourartnet.com/Siku_03/0782/0782_088_114/images/3055_jpg.jpg
                            imageUrl = imageUrl.Replace("thumbnails", "images");
                            Console.WriteLine(imageUrl);
                            // 这里可以添加代码下载图片
                            // 例如使用client.GetAsync(imageUrl)来获取图片内容并保存到文件
                            var arr = imageUrl.Split('/');
                            var fileName = arr[arr.Length - 1];


                            FileHelper.DownLoadFile(imageUrl, path, fileName);
                            LogHelper.WriteLog(imageUrl);
                        }
                        catch (UriFormatException)
                        {
                            // 忽略不正确的URL
                        }
                    }
                }
            }
        }

    }
}
